package com.skytech.component.crawler.task;

import com.skytech.component.crawler.scratch.CreatePageType;
import com.skytech.component.crawler.scratch.TargetRules;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;


public class TaskManager {

    private List<TargetRules> listRules;

    private AtomicInteger index;

    private IndexPageOperation indexPageOperation;


    private int thread = 10;

    private String driverPath;

    private static final Logger log = LoggerFactory.getLogger(TaskManager.class);


    public TaskManager(List<TargetRules> listRules,String driverPath,IndexPageOperation indexPageOperation){
        this.listRules = listRules;
        this.index = new AtomicInteger(listRules.size());
        this.driverPath = driverPath;
        this.indexPageOperation = indexPageOperation;
    }

    private  int next(){
        return index.decrementAndGet();
    }

    public void start(){
        List<Thread> threadList = new ArrayList<>();
        for (int i = 0; i < thread; i++) {
            ConsumerRunnable consumerRunnable = new ConsumerRunnable((name) ->{

                consumer(String.valueOf(name));

            },Integer.toString(i));
            Thread thread = new Thread(consumerRunnable);
            thread.start();
            threadList.add(thread);
        }
        for (Thread task : threadList) {
            try {
                task.join();
            } catch (InterruptedException e) {
                log.error("线程同步失败");
            }
        }
    }

    private void consumer(String name){
        int index = next();
        if(index>=0){
            log.debug("第{}条线程开始",name);
            startRules(listRules.get(index), indexPageOperation);
            consumer(name);
        }
    }

    private void startRules(TargetRules targetRules,IndexPageOperation indexPageOperation){
       // DesiredCapabilities capabilities=new DesiredCapabilities();
       // ChromeDriverService service = new ChromeDriverService.Builder().usingChromeDriverExecutable(new File(driverPath)).usingAnyFreePort().build();
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--headless");
        options.addArguments("--no-sandbox");
       // capabilities.setCapability(ChromeOptions.CAPABILITY, options);
        System.setProperty("webdriver.chrome.driver", driverPath);

        ChromeDriver driver = new ChromeDriver(options);

        try {
            driver.get(targetRules.getSeedUrl());
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            partClickNext(driver, targetRules,null,indexPageOperation);
        } catch (Exception e) {
            log.error("{},{}--超时--{}",targetRules.getId(), targetRules.getId(), e.getMessage());
        }finally {
            driver.quit();
        }
    }

    private void partClickNext(ChromeDriver driver, TargetRules targetRules,String html,IndexPageOperation indexPageOperation) {
        if(indexPageOperation.operate(driver,targetRules)){
            String htmlnew = driver.findElementByTagName("html").getAttribute("outerHTML");
            String currentPath = driver.getCurrentUrl();
            try {
                if (StringUtils.isEmpty(targetRules.getNextButton())) {
                    log.warn("{},{}-没有配置翻页", targetRules.getId(),targetRules.getNextButton());
                    return;
                }

                WebElement element = driver.findElementByXPath(targetRules.getNextButton());

                log.info("{},按钮连接{}",targetRules.getId(), element.getAttribute("href"));
                log.info("{},当前页面{}",targetRules.getId(), driver.getCurrentUrl());
                if (!CreatePageType.url_unchanged.toString().equals(targetRules.getType().trim()) && driver.getCurrentUrl().equals(element.getAttribute("href"))) {
                    //如果两次点击的页面相同停止当前任务
                    log.error("{},{}两次链接地址相同,当前页{}，下一页{}",targetRules.getId(), targetRules.getId(), driver.getCurrentUrl(), element.getAttribute("href"));
                    return;
               }
                if (CreatePageType.url_unchanged.toString().equals(targetRules.getType().trim())) {
                    if (html != null) {
                        if (html.equals(htmlnew)) {
                            log.error("{},{}两次链接内容相同,当前页{}，下一页{}",targetRules.getId(), targetRules.getId(), driver.getCurrentUrl(), element.getAttribute("href"));
                            return;
                        }
                    }
                    htmlnew = html;
                }
                element.click();
                if(CreatePageType.url_unchanged.toString().equals(targetRules.getType().trim())){
                    Thread.sleep(3000);
                }
            } catch (Exception e) {
                log.error("{},{}点击下一页出现问题{}", targetRules.getId(),targetRules.getId(), e.getMessage());
                return;
            }
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            String nextPath = driver.getCurrentUrl();
            if (!CreatePageType.url_unchanged.toString().equals(targetRules.getType().trim()) && currentPath.equals(nextPath)) {
                //点击
                log.error("{},{}点击方法,当前页{}，下一页{}", targetRules.getId(),targetRules.getId(), currentPath, nextPath);
                return;
            }
            partClickNext(driver, targetRules,htmlnew,indexPageOperation);
        }

    }
    public List<TargetRules> getListRules() {
        return listRules;
    }

}
